package com.o2o.controller.shopAdmin;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.o2o.dto.ImageHolder;
import com.o2o.dto.ShopExecution;
import com.o2o.entity.Area;
import com.o2o.entity.PersonInfo;
import com.o2o.entity.Shop;
import com.o2o.entity.ShopCategory;
import com.o2o.enums.ShopStateEnum;
import com.o2o.exceptions.ShopOperationException;
import com.o2o.service.AreaService;
import com.o2o.service.ShopCategoryservice;
import com.o2o.service.ShopService;
import com.o2o.utils.CodeUtil;
import com.o2o.utils.HttpServletRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * package_name:com.o2o.controller.shopAdmin
 * Author:徐亚远
 * Date:2019/11/30 16:05
 * 项目名:o2o
 * Desription:
 **/
@Controller
@RequestMapping("/shopAdmin")
public class ShopManagementController {
    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopCategoryservice shopCategoryservice;
    @Autowired
    private AreaService areaService;

    @RequestMapping(value = "/getshopmanagementinfo", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> getShopManagementInfo(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<>();
        Long shopId = HttpServletRequestUtil.getLong(request, "shopId");
        if (shopId <= 0) {
            Object currentShopObj = request.getSession().getAttribute("currentShop");
            if (currentShopObj == null) {
                modelMap.put("redirect", true);
                modelMap.put("url", "/shopAdmin/getshoplist");
            } else {
                Shop currentShop = (Shop) currentShopObj;
                modelMap.put("redirect", false);
                modelMap.put("shopId", currentShop.getShopId());
            }
        } else {
            Shop currentShop = new Shop();
            currentShop.setShopId(shopId);
            request.getSession().setAttribute("currentShop", currentShop);
            modelMap.put("redirect", false);
        }
        return modelMap;
    }

    @RequestMapping(value = "/getshoplist", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getshopList(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<>();
        //从session中获取i
        PersonInfo user = (PersonInfo) request.getSession().getAttribute("user");
        /*这个删除之后获取不到name在前端*/
        //PersonInfo user = new PersonInfo();
       /* user.setUserId(1L);
        user.setName("admin");
        request.getSession().setAttribute("user",user );
        user = (PersonInfo) request.getSession().getAttribute("user");*/
        List<Shop> shopList = new ArrayList<>();
        try {
            Shop shopCondition = new Shop();
            ShopExecution se = shopService.getShopList(shopCondition, 0, 100);
            modelMap.put("shopList", se.getShopList());
            //列出店铺成功之后,将店铺放入session中作为权限验证依据,即该账号只能操作它自己的店铺
            request.getSession().setAttribute("shopList", se.getShopList());
            modelMap.put("user", user);
            modelMap.put("success", true);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
        }
        return modelMap;
    }

    @RequestMapping(value = "/getShopInitInfo", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getShopInitInfo(HttpServletRequest request) {
        Map<String, Object> modelMap = new HashMap<>();
        List<ShopCategory> shopCategoryList = new ArrayList<>();
        List<Area> areaList = new ArrayList<>();
        try {
            shopCategoryList = shopCategoryservice.queryShopCategory(new ShopCategory());
            areaList = areaService.queryAll();
            modelMap.put("shopCategoryList", shopCategoryList);
            modelMap.put("areaList", areaList);
            modelMap.put("success", true);
            System.out.println("进行了aaagetShopInitInfo");
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("errMsg", e.getMessage());
        }
        return modelMap;
    }

    @RequestMapping(value = "/getShopById", method = RequestMethod.GET)
    @ResponseBody
    private Map<String, Object> getByShopId(HttpServletRequest request) throws IOException {
        Map<String, Object> modelMap = new HashMap<>();
        Long shopId = HttpServletRequestUtil.getLong(request, "shopId");
        if (shopId > -1) {
            try {
                Shop shop = shopService.queryByShopId(shopId);
                //List<ShopCategory> shopCategoryList = n;
                /*获取区域列表*/
                List<Area> areaList = areaService.queryAll();
                modelMap.put("shop", shop);
                modelMap.put("areaList", areaList);
                modelMap.put("success", true);
                //System.out.println("到这里了shopId>-1");
            } catch (Exception e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.toString());
            }
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "empty shopId");
        }
        return modelMap;
    }

    @RequestMapping(value = "/modifyShop", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> modifyShop(HttpServletRequest request) throws IOException {
        System.out.println("执行registShop路由了");
        Map<String, Object> modelMap = new HashMap<>();
        /*验证码验证输入的验证码与生成的验证码是否一致*/
        if (!CodeUtil.checkVerifyCode(request)) {
            modelMap.put("successs", false);
            modelMap.put("errMsg", "输入验证码错误");
            return modelMap;
        }
        /*接受并转换相应的参数,包括店铺信息以及图片信息*/
        String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
        ObjectMapper mapper = new ObjectMapper();
        Shop shop = null;
        try {
            /*把接收到的json数据转换为实体类*/
            shop = mapper.readValue(shopStr, Shop.class);
            System.out.println("jfdshfkjdsh徐亚远:" + shop.toString());
        } catch (Exception E) {
            modelMap.put("success", false);
            modelMap.put("errmsg", E.getMessage());
            System.out.println("jkldsjflk没有接受到数据");
            return modelMap;
        }
        CommonsMultipartFile shopImg = null;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession()
                .getServletContext());
        if (commonsMultipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartHttpServletRequest =
                    (MultipartHttpServletRequest) request;
            shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        }
        /*修改店铺店铺*/
        if (shop != null && shop.getShopId() != null) {
            /*通过session获得用户的信息 ownerid*/
            /*PersonInfo owner = new PersonInfo();
            owner.setUserId(1L);
            shop.setOwner(owner);*/
            ShopExecution se;
            /*File shopImgFile = new File(PathUtil.getImageBasePath()+
                    ImageUtil.generateRandomFileName());*/
            //shopImgFile.createNewFile();
            //inputStreamToFile(shopImg.getInputStream(),shopImgFile );
            try {

                if (shopImg == null) {
                    se = shopService.modifyShop(shop, null);
                } else {
                    ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(), shopImg.getInputStream());
                    se = shopService.modifyShop(shop, imageHolder);
                }
                if (se.getState() == ShopStateEnum.SUCCESS.getState()) {
                    modelMap.put("success", true);
                } else {
                    modelMap.put("success", false);
                    modelMap.put("essMsg", se.getStateInfo());
                }
            } catch (ShopOperationException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            } catch (IOException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            }
            return modelMap;
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "请输入店铺ID");
            return modelMap;
        }
    }

    @RequestMapping(value = "/registShop", method = RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> registShop(HttpServletRequest request) throws IOException {
        System.out.println("执行registShop路由了");
        Map<String, Object> modelMap = new HashMap<>();
        /*验证码验证输入的验证码与生成的验证码是否一致*/
        if (!CodeUtil.checkVerifyCode(request)) {
            modelMap.put("successs", false);
            modelMap.put("errMsg", "输入验证码错误");
            return modelMap;
        }
        /*接受并转换相应的参数,包括店铺信息以及图片信息*/
        String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
        ObjectMapper mapper = new ObjectMapper();
        Shop shop = null;
        try {
            /*把接收到的json数据转换为实体类*/
            shop = mapper.readValue(shopStr, Shop.class);
            System.out.println("jfdshfkjdsh徐亚远:" + shop.toString());
        } catch (Exception E) {
            modelMap.put("success", false);
            modelMap.put("errmsg", E.getMessage());
            System.out.println("jkldsjflk没有接受到数据");
            return modelMap;
        }
        CommonsMultipartFile shopImg = null;
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession()
                .getServletContext());
        if (commonsMultipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multipartHttpServletRequest =
                    (MultipartHttpServletRequest) request;
            shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
        } else {
            modelMap.put("success", false);
            modelMap.put("essMsg", "上传图片不能为空");
            return modelMap;
        }
        /*注册店铺*/
        if (shop != null && shopImg != null) {
            /*通过session获得用户的信息 ownerid*/
            PersonInfo owner = (PersonInfo) request.getSession().getAttribute("user");
            shop.setOwner(owner);
            /*强制获取用户信息*/
           /* PersonInfo owner = new PersonInfo();
            owner.setUserId(1L);
            shop.setOwner(owner);*/

            /*File shopImgFile = new File(PathUtil.getImageBasePath()+
                    ImageUtil.generateRandomFileName());*/
            //shopImgFile.createNewFile();
            //inputStreamToFile(shopImg.getInputStream(),shopImgFile );
            ShopExecution se;
            try {
                ImageHolder imageHolder = new ImageHolder(shopImg.getOriginalFilename(), shopImg.getInputStream());
                se = shopService.addShop(shop, imageHolder);
                if (se.getState() == ShopStateEnum.CHECK.getState()) {
                    modelMap.put("success", true);
                    //该用户可以操作的店铺列表
                    @SuppressWarnings("unchecked")
                    List<Shop> shopList = (List<Shop>) request.getSession().getAttribute("shopList");
                    if (shopList == null || shopList.size() == 0) {
                        shopList = new ArrayList<Shop>();
                    }
                    shopList.add(se.getShop());
                    request.getSession().setAttribute("shopList", shopList);
                } else {
                    modelMap.put("success", false);
                    modelMap.put("essMsg", se.getStateInfo());
                }
            } catch (ShopOperationException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            } catch (IOException e) {
                modelMap.put("success", false);
                modelMap.put("errMsg", e.getMessage());
            }
            return modelMap;
        } else {
            modelMap.put("success", false);
            modelMap.put("errMsg", "请输入店铺信息");
            return modelMap;
        }
    }

    @RequestMapping(value = "/deleteShop/{shopId}")
    @ResponseBody
    public String deleteShop(@PathVariable Long shopId) {
        shopService.deleteShop(shopId);
        System.out.println("success");
        return "success";
    }
    /*
     *//*
     * 返回商品列表页里的ShopCategory列表(二级或一级),以及区域信息列表
     * @param request
     * @return
     * *//*
    @RequestMapping(value = "/listshopspageinfo",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> listShopsPageInfo(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<>();
        //试着从前端请求中获取parentId
        Long parentId = HttpServletRequestUtil.getLong(request,"parentId" );
        List<ShopCategory> shopCategoryList = null;
        if (parentId != -1){
            //如果parentId存在,则取出该一级shopCategory下的二级ShopCategory列表
            try {
                ShopCategory shopCategoryCondition = new ShopCategory();
                ShopCategory parent = new ShopCategory();
                parent.setShopCategoryId(parentId);
                shopCategoryList = shopCategoryservice.getShopCategoryList(shopCategoryCondition);
            }catch (Exception e){
                modelMap.put("success",false );
                modelMap.put("errMsg",e.getMessage() );
            }
        }else {
            try {
                //如果parentId不存在,则取出所有一级ShopCategory(用户在首页选择的是全部商品列表)
                shopCategoryList = shopCategoryservice.getShopCategoryList(null);
            }catch (Exception e){
                modelMap.put("success",false );
                modelMap.put("errMsg",e.getMessage() );
            }
        }
        modelMap.put("shopCategoryList",shopCategoryList );
        List<Area> areaList = null;
        try {
            //获取区域列表信息
            areaList = areaService.queryAll();
            modelMap.put("areaList",areaList );
            modelMap.put("success",true );
            return modelMap;
        }catch (Exception e){
            modelMap.put("success",false );
            modelMap.put("errMsg",e.getMessage() );
        }
        return modelMap;
    }

    *//*
     *获取指定查询条件下的店铺列表
     * @param request
     * @return
     * *//*
    @RequestMapping(value = "/listshops",method = RequestMethod.GET)
    @ResponseBody
    private Map<String,Object> listShops(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<>();
        //获取页码
        int pageIndex = HttpServletRequestUtil.getInt(request,"pageIndex" );
        //获取一页需要显示的数据条数
        int pageSize = HttpServletRequestUtil.getInt(request,"pageSize" );
        //非空判断
        if ((pageIndex> -1)&&(pageSize >-1)){
            //试着获取一级类别Id
            long parentId = HttpServletRequestUtil.getLong(request,"parentId" );
            //试着获取特定二级类别Id
            long shopCategoryId = HttpServletRequestUtil.getInt(request,"shopCategoryId" );
            //试着获取区域Id
            int areaId = HttpServletRequestUtil.getInt(request,"areaId" );
            //试着获取模糊查询的名字
            String shopName = HttpServletRequestUtil.getString(request,"shopName" );
            //获取组合之后的查询条件
            Shop shopCondition = compactShopCondition4Search(parentId,shopCategoryId,areaId,shopName);
            //根据查询条件和分页信息获取店铺列表,并返回总数
            ShopExecution se = shopService.getShopList(shopCondition,pageIndex ,pageSize );
            modelMap.put("shopList",se.getShopList() );
            modelMap.put("count",se.getCount() );
            modelMap.put("success",true);
        }else {
            modelMap.put("success",false );
            modelMap.put("errMsg","empty pageSize or pageIndex" );
        }
        return modelMap;
    }

    *//*
     * 组合条件查询,并将其条件封装到ShopCondition对象里返回
     * @param parentId
     * @param shopCategoryId
     * @param areaId
     * @param shopName
     * @return
     *
     * *//*
    private Shop compactShopCondition4Search(long parentId,long shopCategoryId, int areaId,String shopName){
        Shop shopCondition = new Shop();
        if (parentId !=-1L){
            //查询某个一级ShopCategory下面的所有二级ShopCategory里面的店铺列表
            ShopCategory childCategory = new ShopCategory();
            ShopCategory parentCategory = new ShopCategory();
            parentCategory.setShopCategoryId(parentId);
            childCategory.setParent(parentCategory);
            shopCondition.setShopCategory(childCategory);
        }
        if (shopCategoryId !=-1L){
            //查询某个二级ShopCategory下面的店铺列表
            ShopCategory shopCategory = new ShopCategory();
            shopCategory.setShopCategoryId(shopCategoryId);
            shopCondition.setShopCategory(shopCategory);
        }
        if (areaId!=-1L){
            //查询某个区域Id下的店铺列表
            Area area = new Area();
            area.setAreaId(areaId);
            shopCondition.setArea(area);
        }
        if (shopName !=null){
            //查询名字里包含shopName的店铺列表
            shopCondition.setShopName(shopName);
        }
        //前端展示的店铺都是审核成功的店铺
        shopCondition.setEnableStatus(1);
        return shopCondition;
    }
    */

    /* *//*把CommonsMultipartFile类型的文件转换为file类型的*//*
    private static void inputStreamToFile(InputStream ins, File file) throws IOException {
        FileOutputStream os = null;
        try {
            os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[1024];
            while ((bytesRead = ins.read(buffer)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException("调用inputStreamToFile产生异常:" + e.getMessage());
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (ins != null) {
                    ins.close();
                }
            } catch (IOException e) {
                throw new RuntimeException("inputStreamToFile关闭IO异常:" + e.getMessage());
            }
        }
    }*/
}
